<template>
  <div class="bg_block">
    <headback :title="t('详情')"></headback>
    <div class="total_box light_border">
      <div class="detail_title">{{ t("基本信息") }}</div>
      <div class="total_item">
        <div class="total_name">{{ t("标题") }}</div>  <div class="total_value">  {{ lockItem.title }}  </div>
      </div>
      <div class="total_item">
        <div class="total_name">{{ t("我锁仓的数量") }}</div>  <div class="total_value">  {{ lockItem.amount }} BTC </div>
      </div>
      <div class="total_item">
        <div class="total_name">{{ t("权限所有者") }}</div>  <div class="total_value">   {{ lockItem.owner==store.state.address0? '已放弃权限' : splitAddress(lockItem.owner ) }}  </div>
      </div>
      <div class="total_item">
        <div class="total_name">{{ t("释放接收地址") }}</div>  <div class="total_value">   {{  splitAddress(lockItem.receiveAddress ) }}  </div>
      </div>
      <div class="total_item">
        <div class="total_name">{{ t("推荐人") }}</div>  <div class="total_value">   {{  splitAddress(lockItem.referenceAddress ) }}  </div>
      </div>
      <div class="total_item">
        <div class="total_name">{{ t("推荐人奖励比例（%）") }}</div>  <div class="total_value">   {{    lockItem.referenceRatio * 100 }}  </div>
      </div>
      <div class="total_item">
        <div class="total_name">{{ t("锁定日期") }}</div>  <div class="total_value">   {{    lockItem.lockDate }}  </div>
      </div>
      <div class="total_item">
        <div class="total_name">{{ t("首次释放日期") }}</div>  <div class="total_value">   {{    lockItem.tgeDate }}  </div>
      </div>
      <template v-if="lockItem.tgeBps>0">
      <div class="total_item">
        <div class="total_name">{{ t("首次释放百分百（%）") }}</div>
        <div class="total_value">{{ lockItem.tgeBps * 100 }}</div>
      </div>
      <div class="total_item">
        <div class="total_name">{{ t("循环释放间隔（天）") }}</div>
        <div class="total_value">{{ lockItem.cycle }}</div>
      </div>
      <div class="total_item">
        <div class="total_name">{{ t("循环释放百分比（%）") }}</div>
        <div class="total_value">{{ lockItem.cycleBps * 100 }}</div>
      </div>
    </template>
      <div class="total_item">
        <div class="total_name">{{ t("已解锁数量") }}</div>
        <div class="total_value amount_value">
          {{ lockItem.unlockedAmount }}
        </div>
      </div>
      <div class="total_item">
        <div class="total_name">{{ t("通证合约地址") }}</div>
        <div class="total_value">
          {{ splitAddress(lockItem.token) }}
        </div>
      </div>
      <div class="total_item">
        <div class="total_name">{{ t("备注") }}</div>
        <div class="total_value">
          {{ lockItem.description }}
        </div>
      </div>
    </div>
    <!-- 理财信息 -->
    <div class="total_box light_border" style="margin-top: 14px">
    <div class="detail_title">{{ t("理财信息") }}</div>
    <div class="total_item" style="margin-top: 14px">
      <div class="total_name">{{ t("当前价格") }}</div>
      <div class="total_value">
        1BTC =  {{ store.state.tokenPrice }}USDT
      </div>
    </div>
    <div class="total_item">
      <div class="total_name">{{ t("参与价格") }}</div>
      <div class="total_value"> 1BTC =  {{ lockItem.price }}USDT</div>
    </div>
    <div class="total_item">
      <div class="total_name">{{ t("参与数量") }}</div>
      <div class="total_value">{{ lockItem.amount }} BTC</div>
    </div>
    <div class="total_item">
      <div class="total_name">{{ t("盈利情况") }}</div>
      <div class="total_value">{{ lockItem.alreadyUsdt }}</div>
    </div>
    </div>
    <!-- 理财信息结束 -->

    
    <!-- 释放信息开始 -->
    <div class="total_box light_border" style="margin-top: 14px">
      <div class="detail_title">{{ t("释放信息") }}</div>
      <div>
        <div class="record_item title_color" >
          <div class="record_id">{{ t('解锁编号') }}</div>
          <div class="record_time">{{ t('时间') }}</div>
          <div class="record_amount">{{ t('已解锁的资产') }}</div>
        </div>
        <div class="record_item" :class="{recordGrey:item.status==2,recordActive:item.status==1}" v-for="item in recordList" :key="item.id">
          <div class="record_id">{{ item.id }}</div>
          <div class="record_time">{{ item.date }}</div>
          <div class="record_amount">{{ item.amount }} ({{ item.percentage }}%)</div>
        </div>
      </div>
      <!-- <div class="no_data">暂无数据</div> -->
    </div>
    <!-- 释放信息结束 -->
     <div  class="count_down">
      {{ t('解锁时间') }}
              <van-count-down v-if="nextTime>0" :time="nextTime">
  <template #default="timeData">
    <span class="red_name">{{ timeData.days }}</span>
    <span class="colon">{{ t('day') }}</span>
    <span class="red_name">{{ timeData.hours }}</span>
    <span class="colon">{{ t('hours') }}</span>
    <span class="red_name">{{ timeData.minutes }}</span>
    <span class="colon">{{ t('minutes') }}</span>
    <!-- <span class="block">{{ timeData.seconds }}</span> -->
  </template>
</van-count-down>
     </div>
     <div>
      <van-button :loading="loading" class="confirm_btc" :disabled="isCan"  @click="confirm" type="primary">
        {{ t('解锁') }}
      </van-button>
     </div>
  </div>
</template>
<script setup>
import { showToast } from "vant";
import IndexDBCache from "@/hooks/sql/useOrder.js";
import "vant/es/toast/style";
import { useStore } from "vuex";
import bus from "@/utils/bus.js";
import { ref, reactive, onMounted, computed, onUnmounted } from "vue";
import { useI18n } from "vue-i18n";
import { getDate } from "@/utils/index.js";
const { locale, t } = useI18n();
import bankEth from "@/utils/bankEth";
import eth from "@/utils/eth";
import { splitAddress } from "@/utils/index.js";
import { useRouter } from "vue-router";
const router = useRouter();
const orderDB = new IndexDBCache();
const store = useStore();
const active = ref(0);
const requireImg = (imgPath) => {
  return new URL(`../../assets/images/${imgPath}`, import.meta.url).href;
};
const props = defineProps({
  id: {
    type: [String, Number],
    required: true,
  },
  // 其他 props...
});
const lockItem = ref({});
const goToPage = (value, type) => {
  let query = {};
  router.push({
    name: value,
    query,
  });
};
const isCan = computed(()=>{
  return recordList.value.every(e=>e.status!=1)
})
const nextTime = computed(()=>{
  let data = recordList.value.find(e=>e.status==0)
   if(data){
      const givenDate = new Date(data.date).getTime();
// 计算加上天数后的日期
let dueDate = new Date(givenDate).getTime();
const now = new Date().getTime();
// 计算当前时间与到期时间的差异（毫秒）
const timeDiff = dueDate - now;
if (timeDiff > 0) {
    return timeDiff
} else{
    return 0
}

    }else{
      return 0
    }

})
const generateReleaseSchedule = (item)=> {
 let lockedAmount = item.amount
 let firstReleaseTime = item.tgeDate
 let firstReleasePercentage = item.tgeBps
 let releaseIntervalDays = item.cycle
 let cycleReleasePercentage = item.cycleBps
  const schedule = [];
  let remainingAmount = lockedAmount;
  let currentDate = new Date(firstReleaseTime);
  
  // 首次释放
  const firstReleaseAmount = lockedAmount * firstReleasePercentage;
  remainingAmount -= firstReleaseAmount;
  // 判断首次释放是否到期
  let nowDate = new Date()
  // 判断是否到达时间
  // 判断是否已经解锁
  let isOver = nowDate > new Date(currentDate)
  let isLock = item.unlockedAmount>=firstReleaseAmount
  let status = 0
  if(isOver&&isLock){
    // 已到期已解锁
    status = 2
  }else if(isOver&&!isLock){
    status = 1
    // 已到期未解锁
  }else if(!isOver&&isLock){
    // 未到期提前解锁
    status = 2
  }
 
  if(item.tgeBps==0){
    schedule.push({
    id:1,
    status,
    date: getDate(new Date(currentDate)),
    percentage: 100,
    amount: lockedAmount,
    });
    return schedule;
  }
  schedule.push({
    id:1,
    status,
    date: getDate(new Date(currentDate)),
    percentage: firstReleasePercentage*100,
    amount: firstReleaseAmount,
    remaining: remainingAmount
  });
  
  // 循环释放
  let cycleCount = 1;
  while (remainingAmount > 0) {
    // 计算下一次释放日期
    currentDate.setDate(currentDate.getDate() + releaseIntervalDays);
    
    // 计算本次释放数量（不超过剩余数量）
    const cycleAmount = Math.min(
      lockedAmount * cycleReleasePercentage,
      remainingAmount
    );
    if (cycleAmount <= 0) break;
    
    remainingAmount -= cycleAmount;
    status = 0
    if(nowDate>new Date(currentDate)){
      status = 1
    }
    if(item.amount-item.unlockedAmount<=remainingAmount){
      status = 2
    }
    schedule.push({
      status,
      id:cycleCount+1,
      date:  getDate(new Date(currentDate)),
      percentage: cycleReleasePercentage*100,
      amount: cycleAmount,
      remaining: remainingAmount
    });
    
    cycleCount++;
  }
  
  return schedule;
}
const recordList = ref([])
const loading = ref(false);
const initData = async () => {
  // 获取详情 先获取本地 再获取线上
  lockItem.value = await bankEth.getLockDetail(props.id);
  // 再获取线上
  lockItem.value = await bankEth.getLockById(props.id);

  recordList.value = generateReleaseSchedule(lockItem.value)
  if ((lockItem.value && lockItem.value.id == 0) || !lockItem.value) {
    showToast("该锁不存在,请重新获取");
    return;
  }
};

// 解锁
const confirm = async ()=>{

  loading.value = true
  try {
    let  hex = await  bankEth.ContractWithSinger.unlock(lockItem.value.id)
    // 循环锁
   await hex.wait();
   loading.value = false;
   showToast(t('unlockSuccess'))
   initData()

  } catch (error) {
    let errorStr = JSON.stringify(error)
    if(errorStr&&errorStr.indexOf("Please change the recommender")>=0){
      showToast(t('recommenderIsWrong'))
    }
    else{
      if(store.state.isShowError){
        showToast(t('unlockFail')+errorStr)
      }else{
        showToast(t('unlockFail'))
      }
    } 
    loading.value = false;
  }
  

}
const fn = () => {
  bus.on("init", (value) => {
    initData();
  });
};
onUnmounted(() => {
  bus.off("init");
});
onMounted(() => {
  initData();
});
</script>

<style lang="scss" scoped>

.count_down{
  margin-top:20px;
  text-align: center;
  display: flex;
  line-height: 20px;
  align-items: center;
  // white-space: nowrap;
  justify-content: center;
  .colon{
    color:#232323;
  }
  .red_name{
    color: #f50300;
    padding: 0 3px;
  }
}
.confirm_btc{
  border-radius: 20px;
  margin-top: 8px;
  height: 34px;
}
:deep .van-badge__wrapper {
  display: flex;
  align-items: center;
  color: #eee;
}
.detail_title {
  position: relative;
  height: 40px;
  display: flex;
  align-items: center;
  padding-left: 10px;
  &::before {
    content: " ";
    position: absolute;
    top: 50%;
    left: 0;
    height: 12px;
    width: 4px;
    background: $primary-color;
    transform: translateY(-50%);
  }
}
:deep .van-tabs__nav .van-tabs__line {
  border-radius: 5px;
  bottom: 22px;
}
.bg_block {
  margin-top: 48px;
  padding: 0 14px 30px 14px;
  box-sizing: border-box;
}
.total_box {
  // background: #f2f2f2;
  border-radius: 6px;
  padding: 0 10px;
  box-sizing: border-box;
  .total_item {
    display: flex;
    height: 34px;
    align-items: center;
    // padding-left: 10px;
    justify-content: space-between;
    position: relative;
    // &::before{
    //   content: " ";
    //   position: absolute;
    //   top: 50%;
    //   left: 0;
    //   height: 5px;
    //   width: 5px;
    //   border-radius: 50%;
    //   background: $primary-color;
    //   transform: translateY(-50%);
    // }
    .total_name {
      color: #222;
      font-weight: bold;
    }
    .total_value {
      color: #7a7a7a;
      display: flex;
      align-items: center;
      line-height: 20px;
      gap: 4px;
    }
    .amount_value {
      color: $primary-color;
    }
  }
}
.title_color{
  color: $primary-color;
  font-weight: bold;
}

.record_item{
  display: flex;
  align-items: center;
  line-height:24px;
  justify-content: space-between;
  .record_id{
    width: 60px;
    text-align: center;
  }
  .record_time{
    flex: 1;
    text-align: center;
  }
  .record_amount{
    min-width: 100px;
    text-align: center;
  }
}
.recordActive{
  color: $primary-color;
}
.recordGrey{
  color: #7a7a7a;
}
</style>
